package cn.dnuihyy406.dnuifood_16110100406;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.mob.MobSDK;

import java.util.HashMap;

import cn.dnuihyy406.dnuifood_16110100406.controller.LoginActivity;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.RegisterPage;

public class ForgetPwdActivity extends AppCompatActivity {

    private Button btnVerify;
    private Button btnFinish;
    private ButtonTimeCount btnTimeCount;
    private EditText et_phoneNumber,et_captcha;
    private Button btnBack;
    private TextView tvTitle;

    private String phone,country="86";     // 电话号码
    private String code;  // 验证码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        如果您没有在AndroidManifest中设置appliaction的类名，MobSDK会将这个设置为com.mob.MobApplication，
//        但如果您设置了，请在您自己的Application类中调用：MobSDK.init(this);
        MobSDK.init(this);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_forget_pwd);


        btnVerify = (Button) findViewById(R.id.btn_verify);
        btnFinish = (Button) findViewById(R.id.btn_finish);

        et_phoneNumber=(EditText)findViewById(R.id.et_phoneNumber);
        et_captcha=(EditText)findViewById(R.id.et_captcha);

        btnTimeCount = new ButtonTimeCount(60000, 1000);


        verificationCode();
    }

    /**
     * @ClassName:ButtonBackClickListener
     * @Description:返回到登录界面
     */
    class ButtonBackClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(ForgetPwdActivity.this, LoginActivity.class);
            startActivity(intent);

        }
    }

    /**
     * @author yan
     * @ClassName:ButtonVerifyClickListener
     * @Description:获取验证码的按钮监听器
     */
    class ButtonVerifyClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            btnTimeCount.start();
//            sendCode(ForgetPwdActivity.this);
        }
    }

    /**
     * @author yan
     * @ClassName:ButtonTimeCount
     * @Description:找回密码时验证手机号码
     */
    class ButtonTimeCount extends CountDownTimer {

        /**
         * @param millisInFuture    总时长
         * @param countDownInterval 计时的时间间隔
         */
        public ButtonTimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        /**
         * 计时完成时触发
         */
        @Override
        public void onFinish() {
            btnVerify.setText(R.string.verify_phone);
            btnVerify.setClickable(true);
        }
        /**
         * 计时过程显示
         */
        @Override
        public void onTick(long millisUntilFinished) {
            btnVerify.setClickable(false);
            btnVerify.setTextColor(Color.WHITE);
            btnVerify.setText((millisUntilFinished / 1000) + "秒");
        }
    }
    //    以可视化界面完成操作（即用官方自带的界面）
    public void sendCode(Context context) {
        RegisterPage page = new RegisterPage();
        //如果使用我们的ui，没有申请模板编号的情况下需传null
        page.setTempCode(null);
        page.setRegisterCallback(new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    // 处理成功的结果
                    HashMap<String,Object> phoneMap = (HashMap<String, Object>) data;
                    String country = (String) phoneMap.get("country"); // 国家代码，如“86”
                    String phone = (String) phoneMap.get("phone"); // 手机号码，如“13800138000”
                    // TODO 利用国家代码和手机号码进行后续的操作
                } else{
                    // TODO 处理错误的结果
                }
            }
        });
        page.show(context);
    }
    //    以无界面接口完成操作（即用自己写的界面）
//    public void verificationCode(){
    EventHandler eventHandler = new EventHandler() {
        public void afterEvent(int event, int result, Object data) {
            // afterEvent会在子线程被调用，因此如果后续有UI相关操作，需要将数据发送到UI线程
            Message msg = new Message();
            msg.arg1 = event;
            msg.arg2 = result;
            msg.obj = data;
            new Handler(Looper.getMainLooper(), new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    int event = msg.arg1;
                    int result = msg.arg2;
                    Object data = msg.obj;
                    if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            // TODO 处理成功得到验证码的结果
                            // 请注意，此时只是完成了发送验证码的请求，验证码短信还需要几秒钟之后才送达
                            Toast.makeText(getApplicationContext(), "验证码已经发送", Toast.LENGTH_SHORT).show();

                        } else {
                            // TODO 处理错误的结果
                            ((Throwable) data).printStackTrace();
                            Toast.makeText(ForgetPwdActivity.this, "验证码发送失败", Toast.LENGTH_SHORT).show();
                        }
                    } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            // TODO 处理验证码验证通过的结果
                            Toast.makeText(getApplicationContext(), "验证码验证通过", Toast.LENGTH_SHORT).show();
//                    startActivity(new Intent(ForgetPwdActivity.this, SuccessActivity.class));
                        } else {
                            // TODO 处理错误的结果
                            ((Throwable) data).printStackTrace();
                            Toast.makeText(getApplicationContext(), "验证码错误", Toast.LENGTH_SHORT).show();
                        }
                    }
                    // TODO 其他接口的返回结果也类似，根据event判断当前数据属于哪个接口
                    return false;
                }
            }).sendMessage(msg);
        }
    };
    public void verificationCode(){
        //        注册一个事件回调，用于处理SMSSDK接口请求的结果
        SMSSDK.registerEventHandler(eventHandler);
        btnVerify.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {
                btnTimeCount.start();
//                Toast.makeText(getApplicationContext(), "123", Toast.LENGTH_SHORT).show();
                //SMSSDK.getVerificationCode("1", "4432487596");
//                SMSSDK.getVerificationCode("86", et_phoneNumber.getText().toString());
                // 请求验证码，其中country表示国家代码，如“86”；phone表示手机号码，如“13800138000”
                phone=et_phoneNumber.getText().toString();
                SMSSDK.getVerificationCode(country, phone);
            }

        });
        btnFinish.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {
//                SMSSDK.submitVerificationCode("86", phone, et_captcha.getText().toString());
                // 提交验证码，其中的code表示验证码，如“1357”
                code=et_captcha.getText().toString();
                SMSSDK.submitVerificationCode(country, phone, code);

            }
        });

    }
//    }


    //    protected void onDestroy() {
//        super.onDestroy();
//        SMSSDK.unregisterAllEventHandler();
//    }
    // 使用完EventHandler需注销，否则可能出现内存泄漏
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(eventHandler);
    }
}
